package com.pgytesting.secondhandcar.service.impl;

import com.pgytesting.secondhandcar.dao.McpCarDealerInformationDao;
import com.pgytesting.secondhandcar.dao.McpUserInfoDao;
import com.pgytesting.secondhandcar.dao.OrderNameDao;
import com.pgytesting.secondhandcar.dao.VehicleInformationDao;
import com.pgytesting.secondhandcar.model.*;
import com.pgytesting.secondhandcar.service.LoanRepaymentInformationService;
import com.pgytesting.secondhandcar.service.McpUserInfoService;
import com.pgytesting.secondhandcar.model.OrderName;
import com.pgytesting.secondhandcar.model.Pagination;
import com.pgytesting.secondhandcar.model.ReviewInformation;
import com.pgytesting.secondhandcar.service.ExamineInformationService;
import com.pgytesting.secondhandcar.service.OrderNameService;
import com.pgytesting.secondhandcar.util.SessionUtil;
import com.pgytesting.secondhandcar.util.UtilMethod;
import com.pgytesting.secondhandcar.vo.Parameters;
import com.pgytesting.secondhandcar.vo.ResponseMessage;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 订单(OrderName)表服务实现类
 *
 * @author makejava
 * @since 2019-08-12 18:55:58
 */
@Slf4j
@Service("orderNameService")
public class OrderNameServiceImpl implements OrderNameService {
    @Resource
    private OrderNameDao orderNameDao;

    @Resource
    McpUserInfoDao mcpUserInfoDao;

    @Resource
    McpCarDealerInformationDao mcpCarDealerInformationDao;

    @Resource
    VehicleInformationDao vehicleInformationDao;

    @Autowired
    ExamineInformationService examineInformationService;

    @Resource
    LoanRepaymentInformationService loanRepaymentInformationService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrderName queryById(String id) {
        return this.orderNameDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param pagination 分页类
     * @return 对象列表
     */
    @Override
    public ResponseMessage queryAllByLimit(Pagination pagination) {
        List<OrderName> resultList = null;
        try {
            resultList = this.orderNameDao.queryAllByLimit(pagination);
        } catch (Exception e) {
            log.error("查询订单数据异常", e);
            ResponseMessage.errorResponse("查询订单数据异常");
        }
        return ResponseMessage.successResponse(resultList, "查询订单数据成功");
    }

    /**
     * 条件查询多条数据
     *
     * @param orderName 实例对象
     * @return 对象列表
     */
    @Override
    public List<OrderName> queryAll(OrderName orderName) {
        return this.orderNameDao.queryAll(orderName);
    }

    /**
     * 新增数据
     *
     * @param vehicleInformation 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public ResponseMessage insert(VehicleInformation vehicleInformation) {
        // 首先进行申请人姓名验证
        String userName = vehicleInformation.getUserName();
        String userNumber = SessionUtil.getSessionMcpUser().getUserNumber();
        // 数据库查询数据，进行用户名称验证
        McpUserInfo mcpUserInfo = mcpUserInfoDao.queryById(userNumber);
        if (!ObjectUtils.isEmpty(mcpUserInfo)) {
            if (!userName.equals(mcpUserInfo.getUserName())) {
                return ResponseMessage.errorResponse("申请人姓名与实名认证不相同");
            }
        } else {
            return ResponseMessage.errorResponse("非法请求，请重新登陆");
        }
        // 进行车商邀请码验证,使用对象的id来存储车商邀请吗
        McpCarDealerInformation dealerInformation = mcpCarDealerInformationDao.queryByCode(vehicleInformation.getId());
        if (ObjectUtils.isEmpty(dealerInformation)) {
            return ResponseMessage.errorResponse("车商邀请码有误");
        }

        // 插入操作人员
        vehicleInformation.setCreatedBy(SessionUtil.getSessionMcpUser().getPhoneNumber());
        // 生成车辆ID
        vehicleInformation.setId(UtilMethod.getUniqueCode());
        this.vehicleInformationDao.insert(vehicleInformation);
        // 生成订单信息
        OrderName orderName = new OrderName();
        // 生成订单ID
        orderName.setId(UtilMethod.getUniqueCode());
        // 绑定销售账号
        orderName.setSalesUserNumber(dealerInformation.getUserNumber());
        // 绑定用户ID
        orderName.setUserNumber(userNumber);
        // 新增订单人￿￿￿
        orderName.setCreatedBy(userNumber);
        // 绑定车辆ID
        orderName.setVehicleInformationId(vehicleInformation.getId());
        // 添加订单状态
        orderName.setOrderStatus(Parameters.ORDER_21001);
        // 更新贷款信息
        LoanRepaymentInformation information = new LoanRepaymentInformation();

        information.setId(UtilMethod.getUniqueCode());
        information.setLoanAmount(vehicleInformation.getApplyForCarPrice());
        information.setLoanPeriod(vehicleInformation.getDeadline());
        information.setCreatedBy(mcpUserInfo.getPhoneNumber());
        // 更新贷款信息
        loanRepaymentInformationService.insert(information);
        // 订单信息更新贷款ID
        orderName.setLoanRepaymentInformationId(information.getId());
        this.orderNameDao.insert(orderName);
        Map map = new HashMap();
        map.put("orderId", orderName.getId());
        return ResponseMessage.successResponse(map, "初步申请成功");
    }

    /**
     * 修改数据
     *
     * @param orderName 实例对象
     * @return 实例对象
     */
    @Override
    public OrderName update(OrderName orderName) {
        this.orderNameDao.update(orderName);
        return this.queryById(orderName.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.orderNameDao.deleteById(id) > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void operatorsExamineCredit(String id, Integer status, Integer state) {
        Integer examineId = examineInformationService.insert(state);
        OrderName on = new OrderName();
        on.setId(id);
        on.setCarrierCreditReview(examineId.toString());
        on.setUpdatedBy(SessionUtil.getSessionAdmin().getId().toString());
        on.setOrderStatus(status);

        orderNameDao.update(on);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public ResponseMessage managementExamineCredit(String id, Integer status, Integer state) {
        OrderName o = orderNameDao.queryById(id);
        if (o == null) {
            return ResponseMessage.errorResponse("未查询到对应的订单");
        }

        if (o != null && o.getCarrierCreditReview() == null) {
            return ResponseMessage.errorResponse("运营商未审核，资方还不能进行审核");
        }

        Integer examineId = examineInformationService.insert(state);
        OrderName on = new OrderName();
        on.setId(id);
        on.setCreditEvaluation(examineId.toString());
        on.setUpdatedBy(SessionUtil.getSessionAdmin().getId().toString());
        on.setOrderStatus(status);

        orderNameDao.update(on);

        if (state.equals(0)) {
            return ResponseMessage.successResponse("审核征信通过成功");
        } else {
            return ResponseMessage.successResponse("审核征信驳回成功");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void applyLoanExamine(String id, Integer status, Integer state) {
        Integer examineId = examineInformationService.insert(state);
        OrderName orderName = new OrderName();
        orderName.setId(id);
        orderName.setOrderStatus(status);
        orderName.setUpdatedBy(SessionUtil.getSessionAdmin().getId().toString());
        orderName.setPhotoMaterialAudit(examineId.toString());

        orderNameDao.update(orderName);
    }

    @Override
    public List<Map<String, Object>> queryCreditReporting() {
        OrderName orderName = new OrderName();
        orderName.setOrderStatus(Parameters.ORDER_24004);
        orderName.setStatus(0);
        return orderNameDao.queryCreditReporting(orderName);
    }


    @Override
    public ResponseMessage queryUserAll(Pagination pagination) {
        // 获取用户ID
        String mcpCarUser = SessionUtil.getSessionMcpCar().getUserNumber();
        // 根据用户ID查询到用户关联的订单信息
        OrderName orderName = new OrderName();
        orderName.setSalesUserNumber(mcpCarUser);
        List<OrderName> orderList = orderNameDao.queryAll(orderName);
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 需要查询对应的用户信息，模拟分页查询，不进行一次性渲染，以防止大批量访问数据库导致数据库服务器压力大
        orderList.forEach(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", o.getId());
            map.put("userName", mcpUserInfoDao.queryById(o.getUserNumber()).getUserName());
            map.put("createTime", o.getCreatedTime());
            map.put("status", o.getOrderStatus());
            resultList.add(map);
        });
        return ResponseMessage.successResponse(resultList, "查询用户订单信息成功");
    }


    /**
     * 查询订单信息
     *
     * @param orderId 订单Id
     * @return
     */
    @Override
    public ResponseMessage queryUseOrder(List<String> orderId) {
        StringBuilder sf = new StringBuilder();
        for (int i = 0; i < orderId.size(); i++) {
            if (i == 0) {
                sf.append("\"" + orderId.get(i) + "\"");
            } else {
                sf.append(",\"" + orderId.get(i) + "\"");
            }
        }
        List<Map<String, Object>> list = orderNameDao.queryListOrderId(String.valueOf(sf));
        return ResponseMessage.successResponse(list, "查询订单信息成功");
    }


}